------------
-- map.lua new version
-- 用于生成 map.json 文件，该文件保存着所有 wiki 链接对应关系
-- 该程序思路 遍历目录找出 md 文件，读取并提取链接，然后生成 map.json 文件
-- @author 恐咖兵糖 <0@ftls.xyz>
print("Initializing map...")

local ob = require("script/ob")
local json = require("script/json")

-- 变量

local filesInfo = {}

function string.starts(String,Start)
    return string.sub(String,1,string.len(Start))==Start
 end
 
 function string.ends(String,End)
    return End=='' or string.sub(String,-string.len(End))==End
 end

 local function isDirectory(path)
    local p = io.popen('cd "'..path..'" 2>&1')
    local result = p:read('*a')
    p:close()
    return result == ''
end

local function processMarkdownFiles(directory)
    print(directory)

    local dir = io.popen('ls "' .. directory .. '"')
    for file in dir:lines() do
        if file ~= "." and file ~= ".." then
            
            local filePath = directory .. "/" .. file
            local fileAttr = io.popen('file "' .. filePath .. '"'):read('*a')
            if fileAttr:match("text") and filePath:match("%.md$") then
                -- 提取文件信息
                local yaml, text = ob.extract_yaml_and_content(ob.read(filePath))
                    -- 替换链接
                local nText, links = ob.processLinks(text)
                -- TODO 将新文本写入 obFile.key + ".md" 文件
                -- 保存所有链接
                local key = string.sub(filePath, 9 , string.len(filePath) - 3) -- content/xxx.md -> xxx
                -- if end with /_index 
                if string.ends(key, "/_index") then
                    key = string.sub(key, 1, string.len(key) - 7)
                end
                local fileInfo = {
                    key = key, 
                    links = links
                }
                table.insert(filesInfo, fileInfo)
            elseif isDirectory(filePath) then
                -- 处理子目录
                processMarkdownFiles(filePath)
            end
        end
    end
end

local result = processMarkdownFiles("content/kkbt")


-- 将 JSON 字符串写入文件
local file = io.open("data/pre_map.json", "w")
file:write(json.encode(filesInfo))
file:close()
-- 
-- [{
--         "key": "kkbt/病娇",
--         "links": ["kkbt/清姬","kkbt/清姬","kkbt/清姬"]
-- },...]

local function uniquePairs(list)
    local seen = {}
    local result = {}
    for _, pair in ipairs(list) do
        local key = pair[1] .. ":" .. pair[2] -- 使用键和值组合成一个字符串来检查唯一性
        if not seen[key] then
            seen[key] = true
            table.insert(result, pair)
        end
    end
    return result
end


-- 函数用于处理每个对象
local function processObject(obj)
    local result = {}
    for _, link in ipairs(obj.links) do
        table.insert(result, {obj.key, link})
    end
    return result
end

-- 遍历并处理解码后的数据
local processedResult = {}
for _, obj in ipairs(filesInfo) do
    local result = processObject(obj)
    -- 如果不为空
    for _, v in ipairs(result) do
        table.insert(processedResult, v)
    end
end

local finalResult = uniquePairs(processedResult)


local file = io.open("data/map.json", "w")
file:write(json.encode(finalResult))
file:close()